/**
 * 导入数据模板 用户
 */
let userModule = require("../models/user");

// 导入预约记录模板
let appointmentRecordModule = require('../models/appointmentRecord.js')
let Token = require('../utils/jwtutil')     //TOKEN模块

const timeFormater = require('time-formater') //格式化时间插件
const getNewTime = () => timeFormater().format("YYYY-MM-DD HH:mm:ss") //当前时间获取


/**
 * 用户注册
 */
const registerUserControl = (req, res) => {
  console.log(req.file);
  // res.send({
  //   code:1,
  //   headerimg:req.body.headerImg
  // })
  let { username, password, nickname, fullname, sex, age } = req.body;

  // 头像路径名
  let pathImg = `${req.file.destination}${req.file.filename}`

  // console.log(pathImg);
  // 利用模板创建一条数据
  let userM = new userModule({
    //用户名
    username,
    // 密码
    password,
    // 昵称
    nickname,
    // 姓名
    fullname,
    // 头像
    headerimg: pathImg,
    // 性别
    sex,
    // 年龄
    age,
  });

  userM
    .save()
    .then(() => {
      res.send({
        Code: 1,
        info: "注册成功",
      });
    })
    .catch((e) => {
      console.log("系统错误》》" + e);
      res.send({
        Code: -1,
        info: "注册失败！",
      });
    });
};

// 用户登录
const loginUserControl = (req, res) => {
  let { username, password } = req.body;
  console.log(username, password);
  userModule.findOne({ username, password }).then((data) => {
    if (data) {
      let { nickname, headerimg, fullname, _id, sex, age } = data;
      // 生成TOKEN
      let token = Token.encrypt({username,password})
      res.send({
        Code: 1,
        info: {
          nickname,
          headerimg,
          fullname,
          _id,
          sex,
          age,
        },
        token
      });
    } else {
      res.send({
        Code: -1,
      });
    }
  });
};

//用户修改
const updateUSerControl = (req, res) => {
  res.send({
    Code: 1,
    Text: "用户修改成功！",
  });
};

//用户预约  appointmentRecordModule
const yYControl = (req, res) => {
  let { id, nickname } = req.body

  new appointmentRecordModule({
    // 预约时间
    time: getNewTime(),
    // 预约id
    id,
    nickname
  })
    .save()
    .then(() => {
      console.log('成功');
      res.send({
        Code: 1
      })
    })
    .catch(err => {
      console.log('出错！》》》' + err)
      res.send({
        Code: -1
      })
    })
}

// 获取个人预约记录
const getAppointment = (req, res) => {

  let { id } = req.query
  console.log(id);
  appointmentRecordModule.findOne({ id }).then(data => {
    if (data) {
      res.send({
        Code: 1,
        info: data
      })
    } else {
      res.send({
        Code: 0
      })
    }

  }).catch(e => {
    res.send({
      Code: -1,
      data: '错误' + e
    })
  })
}

module.exports = { registerUserControl, loginUserControl, updateUSerControl, yYControl, getAppointment };
